
#include <windows.h>
#include <string.h>
#include <time.h>
#include "cfort.h"

#define WINCLOCKS_PER_SEC 10000000

static time_t  init_elapsed = 0;
static ULONGLONG  init_cpu = 0;
static int     is_time_initialised = 0;
static HANDLE  hProcess = 0;



static void init_time(void)
{
    FILETIME lpCreationTime, lpExitTime, lpKernelTime, lpUserTime;
    ULARGE_INTEGER qword;

    if (is_time_initialised)
      return;

    hProcess = GetCurrentProcess();
    time(&init_elapsed);
    GetProcessTimes(hProcess,&lpCreationTime,&lpExitTime,&lpKernelTime,&lpUserTime);
    memcpy(&qword,&lpKernelTime,sizeof(FILETIME));
    init_cpu = qword.QuadPart ;
    memcpy(&qword,&lpUserTime,sizeof(FILETIME));
    init_cpu += qword.QuadPart ;
    is_time_initialised = 1;
}

void FortranName(PCLOCK,pclock) (Real* cpu, Real* elapsed)
{
    FILETIME lpCreationTime, lpExitTime, lpKernelTime, lpUserTime;
    ULARGE_INTEGER qword;
    ULONGLONG current_cpu;
    time_t current_elapsed;

    if (!is_time_initialised)
      init_time();

    time(&current_elapsed);
    *elapsed = (Real)(difftime(current_elapsed,init_elapsed));

    GetProcessTimes(hProcess,&lpCreationTime,&lpExitTime,&lpKernelTime,&lpUserTime);
    memcpy(&qword,&lpKernelTime,sizeof(FILETIME));
    current_cpu = qword.QuadPart;
    memcpy(&qword,&lpUserTime,sizeof(FILETIME));
    current_cpu += qword.QuadPart;
    *cpu = (double)(((current_cpu - init_cpu )/(ULONGLONG)WINCLOCKS_PER_SEC)) ;
}

